#include "Timer.h"
//---------------------------------------------------------------------------------------------//
float			Timer::_fTimeBetweenFrames = 0;
float			Timer::_MeasureFpsSample = 0;
int				Timer::_iFPS = 0;
long int		Timer::_IFrameCounter = 0;
float			Timer::_lockFps = 0;
float			Timer::_accum = 0;

LARGE_INTEGER	Timer::_performanceCount1;
LARGE_INTEGER	Timer::_performanceCount2;
LARGE_INTEGER	Timer::_frequency;
//---------------------------------------------------------------------------------------------//
void Timer::Start()
{
	DWORD_PTR oldmask = NULL;
	oldmask = SetThreadAffinityMask(GetCurrentThread(), 1); 
	QueryPerformanceFrequency(&_frequency);
	QueryPerformanceCounter(&_performanceCount1);
	SetThreadAffinityMask(GetCurrentThread(), oldmask);

	_fTimeBetweenFrames = 0;
	_MeasureFpsSample = 0;
	_iFPS = 0;
	_IFrameCounter = 0;
	_accum = 0;
}
//---------------------------------------------------------------------------------------------//
void Timer::Measure() 
{
	static float dt = 0;

	static DWORD_PTR oldmask=NULL;

	oldmask=SetThreadAffinityMask(GetCurrentThread(), 1); 

	QueryPerformanceCounter(&_performanceCount2);

	SetThreadAffinityMask(GetCurrentThread(), oldmask);

	dt = (float)(((double)(_performanceCount2.QuadPart-_performanceCount1.QuadPart)*1000)/(double)(_frequency.QuadPart));

	if (dt >= 0) {
		_fTimeBetweenFrames=dt;
		_performanceCount1=_performanceCount2;
	} else {
		_fTimeBetweenFrames=0;
	}

	_MeasureFpsSample+= _fTimeBetweenFrames;

	if (_lockFps > 0) {
		_accum += _fTimeBetweenFrames;
		if (_accum >= _lockFps) {
			_accum -= _lockFps*(int)(_accum/_lockFps);
			_fTimeBetweenFrames = _lockFps;
			//_IFrameCounter++;
		} else
			_fTimeBetweenFrames = 0;
	} //else {
		_IFrameCounter++;
	//}

	if (_MeasureFpsSample>=1000)
	{
		_MeasureFpsSample-=1000;
		_iFPS=(int)_IFrameCounter;
		_IFrameCounter=0;
	}
}
//---------------------------------------------------------------------------------------------//
float Timer::GetDT()
{
	return _fTimeBetweenFrames;
}
//---------------------------------------------------------------------------------------------//
int Timer::GetFPS()
{
	return _iFPS;
}
//---------------------------------------------------------------------------------------------//
void Timer::SetLockFPS(float fps)
{
	if (fps) 
		_lockFps = (float)(1.0f/fps)*1000.0f; 
	else
		_lockFps = 0;
}